package com.wgj.android.accesslibility.job;

import android.accessibilityservice.AccessibilityService;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PermissionInfo;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jiaai.xui.adapter.XRecyclerViewAdapter;
import com.jiaai.xui.adapter.XViewHolder;
import com.jiaai.xui.adapter.decoration.DividerDecoration;
import com.jiaai.xui.utils.XDateUtils;
import com.jiaai.xui.utils.XDensityUtils;
import com.jiaai.xui.utils.log.XLog;
import com.jiaai.xui.view.widget.XToast;
import com.wgj.android.R;
import com.wgj.android.accesslibility.AccessibilityHelper;
import com.wgj.android.accesslibility.IStatusBarNotification;
import com.wgj.android.accesslibility.config.WXConfginUtil;
import com.wgj.android.accesslibility.config.WXIDManage;
import com.wgj.android.accesslibility.config.WXPageUIManage;
import com.wgj.android.accesslibility.service.WGJAccessServier;
import com.wgj.android.http.weixin.WeiXinCacheUtil;
import com.wgj.android.http.weixin.model.WXInfo;
import com.wgj.android.ui.activity.MainActivity;
import com.wgj.android.utils.AccessibilityUtil;
import com.wgj.android.utils.CacheUtils;
import com.wgj.android.utils.Timer;

import java.util.ArrayList;
import java.util.List;

/**
 * ========================================
 * 作    者： 佳爱网络有限公司(wwww.jiaailove.com)
 * 版    本： 1.0
 * 创建日期：  2017/12/14
 * 描    述：
 * 修订历吏：
 * =========================================
 */
public class WXCleanFriendsJob implements AccessbilityJob {
    private int pageIndexOf=0;
    private String className="";
    private static  final  int CHECK=1;
    private static  final  int CHECK_END=2;//检测完成
    private static final String TAG = "WXCleanFriendsJob";
    private boolean isClickContact=false;//是否已点击联系人

    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;
    private WGJAccessServier service;
    private  static int weixinversion=0;

    private  List<String> JSFirends=new ArrayList<>();

    private boolean viewAdded = false;// 透明窗体是否已经显示
    private View startWarp;
    private View mainWarp;
    private Chronometer time3;
    private View view;// 透明窗体
    private View a1;
    private TextView timepicker;
    private  XRecyclerViewAdapter adapter;
    private  TextView msgText;//进程消息
    private  TextView tvCleanNumber;
    private  TextView tvStatus;//好友状态
    private  ImageView animIcon;
    private  RecyclerView recyclerView;
    private PowerManager.WakeLock wakeLock;

    private int totalCleanNum;
    private  String currentName="";

    private  boolean isJSFans=false;
    private boolean isModifyNickeName=false;
    private  boolean isModifyNickeNameEnd=false;
    private AccessibilityNodeInfo currentNodeInfo;

    private  int indexOf=0;//当前屏幕已检测的索引
    private  static int cleanNumber=0;//当前已清理的人数
    private  static String shareContent="";
    /**
     * 已检测的
     */
    private ArrayList<String> cleans=new ArrayList<>();

    private  ArrayList<String> filters=new ArrayList<>();
    @Override
    public String getTargetPackageName() {
        return "com.tencent.mm";
    }

    @Override
    public void onCreateJob(AccessibilityService service) {
        /**常亮*/
        PowerManager pm = (PowerManager) service.getApplication().getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "liveTAG");
        wakeLock.acquire();
        filters.add("微信团队");
        filters.add("微信支付小管家");
        filters.add("高兴");
        filters.add("文件传输助手");
        totalCleanNum=WXConfginUtil.getCheckNumber();
        cleans= WeiXinCacheUtil.getCleans(service.getApplication());
        shareContent="/:share您好,我是"+CacheUtils.getMember().getM_nick()+"，我为旺旺通代言,这是一款智能生活服务APP:\n" +
                "10元可以做代理\n" +
                "10元可以做创客\n" +
                "10元可以锁定客户\n" +
                "10元可以打造万人团队\n" +
                "10元可以实现你的梦想\n" +
                "小生意，大财富，百万创业基金等你拿！安全，可靠，便捷，放心点击链接下载 "+ CacheUtils.getMember().getShareUrl();
        this.service= (WGJAccessServier) service;
    }
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onReceiveJob(final AccessibilityEvent event) {
            className=event.getClassName().toString();
            if(!viewAdded &&!WXPageUIManage.isMainUI(className)){
                AccessibilityHelper.performBack(service);
                return;
            }
          if(WXPageUIManage.isMainUI(className)){//在微信主界面
                    if(!viewAdded){
                        createWindow();
                        return;
                    }
                    if(!isJSFans){
                        onSelectContact();
                        return;
                    }
                    if(isJSFans){
                        try {
                            toContactPage();
                            getListView().getChild(indexOf);
                            currentNodeInfo.getParent().performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
                            Thread.sleep(1000);
                            AccessibilityNodeInfo nodeInfo=AccessibilityHelper.findNodeInfosByText(service.getRootInActiveWindow(),"设置备注及标签");
                            if(nodeInfo!=null){
                                AccessibilityHelper.performClick(nodeInfo);
                            }else {
                                onSelectContact();
                                return;
                            }
                        } catch (Exception e) {
                            Log.e(TAG,"清理僵尸粉出错 error:"+e.getMessage());
                            return;
                        }

                    }

            }
            if(WXPageUIManage.isContactInfoUI(className)){//在微信个人祥细资料页面
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                         AccessibilityNodeInfo sendMsgBut=AccessibilityHelper.findNodeInfosByText(service.getRootInActiveWindow(),"发消息");
                         if(sendMsgBut==null || !sendMsgBut.isEnabled()){
                             AccessibilityHelper.performBack(service);
                         }else {
                             //发消息按钮
                             AccessibilityHelper.performClick(sendMsgBut);
                         }
                         handler.postDelayed(new Runnable() {
                             @Override
                             public void run() {
                                 if(WXPageUIManage.isContactInfoUI(className)){
                                     AccessibilityHelper.performBack(service);
                                 }
                             }
                         },500);

                    }
                },300);

                return;
            }
            if(WXPageUIManage.isChatRoomUI(className)){ //在微信聊天界面
                sendMessage();
                return;
            }

            if(WXPageUIManage.isContactRemarkInfoModUI(className)){
                modifyNickName();
                return;
            }

    }

    @Override
    public void onStopJob() {
        Intent intent=new Intent(service.getApplication(), MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        service.getApplication().startActivity(intent);
        WXConfginUtil.setIsOpenCleanFirend(false);

        cleanNumber=0;
        totalCleanNum=0;
        viewAdded=false;
        indexOf=0;
        time3.stop();
        if(windowManager!=null && view!=null){
            windowManager.removeView(view);
        }
        view=null;
        service.stopCleanJob();
        synchronized (this) {
            // sanity check for null as this is a public method
            if (wakeLock != null) {
                XLog.d("Releasing wakelock");
                try {
                    wakeLock.release();
                } catch (Throwable th) {
                    XLog.e("ignoring this exception, probably wakeLock was already released");

                }
            } else {
                // should never happen during normal workflow
                XLog.e("Wakelock reference is null");
            }
        }
    }

    @Override
    public void onNotificationPosted(IStatusBarNotification event) {

    }

    @Override
    public void setWeiXingVersion(int version) {
        weixinversion=version;
    }

    @Override
    public boolean isEnable() {
        return false;
    }





    /**
     * 转到通讯录并点击好友
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void toContactPage(){
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        AccessibilityNodeInfo nodeInfo=AccessibilityHelper.findNodeInfosByText(service.getRootInActiveWindow(),"通讯录");
        if(nodeInfo!=null){
            /**
             * 跳转到通讯录中
             */
            AccessibilityHelper.performClick(nodeInfo);
        }else {
            checkIsBackground();
        }

    }

    /**
     * 检测联系人
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private  void   selectContact(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(300);
                    List<AccessibilityNodeInfo>  contacts=service.getRootInActiveWindow().findAccessibilityNodeInfosByViewId(WXIDManage.getContactItemId(weixinversion));
                    if(cleanNumber==totalCleanNum){
                        onStopJob();
                        return ;
                    }
                    if(contacts!=null){
                        if(indexOf<=contacts.size()-1){
                            AccessibilityNodeInfo nodeInfo=contacts.get(indexOf);
                            currentName=nodeInfo.getText().toString();
                            Message message =handler.obtainMessage();//发送一个消息，该消息用于在handleMessage中区分是谁发过来的消息；
                            message.what = CHECK;
                            handler.sendMessage(message);
                            if(!cleans.contains(currentName) && currentName.indexOf("僵尸粉")<0  && !filters.contains(currentName)){
                                /**
                                 * 没有检测过的则直接进行检测
                                 */
                                cleans.add(currentName); //添加到已检测记录中
                                WeiXinCacheUtil.saveCleans(service.getApplication(),cleans);//绶存
                                cleanNumber++;
                                indexOf++;
                                currentNodeInfo=nodeInfo;
                                AccessibilityHelper.performClick(currentNodeInfo);
                                return;
                            }else {
                                /**
                                 * 跳过当前联系人
                                 */
                                indexOf++;
                                Message message1 =handler.obtainMessage();//发送一个消息，该消息用于在handleMessage中区分是谁发过来的消息；
                                message1.what = CHECK_END;
                                message1.arg1=1;
                                handler.sendMessage(message1);
                                 selectContact();
                                 return;
                            }
                        }else {
                            /**
                             * 超过一屏后重置索引和滑动一屏距离重新选择联系人
                             */
                            if(AccessibilityHelper.findNodeInfosByText(service.getRootInActiveWindow(),"位联系人")!=null){
                                onStopJob();
                                XToast.success("检测已完成");
                                return ;
                            }

                            AccessibilityNodeInfo listView=getListView();
                            if(listView!=null){
                                indexOf=0;
                                listView.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
                                selectContact();
                                return;
                            }else {
                                checkIsBackground();
                            }

                        }
                    }
                }catch (final Exception e){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Log.e(TAG,"检测联系人"+e.getMessage());
                            XToast.error("发生错误,请重新开始",3000);
                            onStopJob();
                        }
                    });
                    return ;
                 }
            }
        }).start();

    }
    private AccessibilityNodeInfo getListView(){

        return  AccessibilityHelper.findNodeInfosById(service.getRootInActiveWindow(), WXIDManage.getContactListViewId(weixinversion));//获取通讯录
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void  onSelectContact(){
        if(getListView()==null){
            toContactPage();
        }
        selectContact();
    }
    /**
     * 发送信息
     */
    private  void sendMessage(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try{
                    if(AccessibilityHelper.findNodeInfosByText(service.getRootInActiveWindow(),"按住说话")!=null){
                        /**
                         * 如果当前为语消息则转到文本消息
                         */
                        AccessibilityHelper.performClick(AccessibilityHelper.findNodeInfosById(service.getRootInActiveWindow(),WXIDManage.getWieXinVoiceId(weixinversion)));
                    }
                    /**
                     * 获取消息输入框
                     */

                    AccessibilityNodeInfo msgInput = service.getRootInActiveWindow().findFocus(AccessibilityNodeInfo.FOCUS_INPUT);
                    if (msgInput == null) {
                        //如果没有找到输入框则放弃检测当前好友
                        AccessibilityHelper.performBack(service);
                        return;
                    }
                    /**
                     * 发送检测问候语
                     */
                    Bundle arguments = new Bundle();
                    arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, shareContent);
                   // arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, "圣蛋快乐");
                    msgInput.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT,arguments);
                    AccessibilityNodeInfo sendBut=AccessibilityHelper.findNodeInfosByText(service.getRootInActiveWindow(),"发送");
                    if(sendBut!=null){
                        sendBut.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }else {
                        AccessibilityHelper.performBack(service);
                    }
                    checkIsMyFirend();
                }catch (Exception e){
                    Log.e(TAG,"发送信息异常!"+e.getMessage());
                    AccessibilityHelper.performBack(service);

                }
            }
        },300);


    }

    /**
     * 检测是否是我的好友
     */
    private void  checkIsMyFirend(){
        pageIndexOf=0;
        try{
            try {
                Thread.sleep(1000);
            }catch (Exception e){

            }

            List<AccessibilityNodeInfo> nodeInfo=service.getRootInActiveWindow().findAccessibilityNodeInfosByText("朋友验证");

            if(nodeInfo.size()>0){
                isJSFans=true;

                Message message =handler.obtainMessage();
                message.what = CHECK_END;
                message.arg1=0;
                handler.sendMessage(message);


            }else {
                Message message =handler.obtainMessage();
                message.what = CHECK_END;
                message.arg1=1;
                handler.sendMessage(message);
            }

        }catch (Exception e){
            Log.e(TAG,"检测是否是我的好友发生异常:"+e.getMessage());
        }
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
            try{
                  AccessibilityHelper.performBack(service);
            }catch (Exception e){
                Log.e(TAG,e.getMessage()) ;
            }
            }
        },300);


    }

    private void  checkIsBackground(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(!AccessibilityUtil.isBackground(service.getApplication())){
            ComponentName comp = new ComponentName("com.tencent.mm","com.tencent.mm.ui.LauncherUI");
            Intent it = new Intent();
            it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//需要加这个不然会报错
            it.setComponent(comp);
            service.getApplication().startActivity(it);
            return;
        }
    }

    /**
     * 修改昵称
     */
    private  void modifyNickName(){
        AccessibilityHelper.performClick(AccessibilityHelper.findNodeInfosById(service.getRootInActiveWindow(), WXIDManage.getNickNameTextId(weixinversion)));
        try {

            AccessibilityNodeInfo nameInput=AccessibilityHelper.findNodeInfosById(service.getRootInActiveWindow(), WXIDManage.getNickNameInputId(weixinversion));
            if(nameInput==null){
                AccessibilityHelper.performBack(service);
                return;
            }
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){// android 5.0有上
                Bundle arguments = new Bundle();
                arguments.putCharSequence(
                        AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, "A00僵尸粉-"+currentName.replaceAll("A00僵尸粉-",""));
                nameInput.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);


            }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { //android 4.3 版本及以上
                ClipboardManager clipboard = (ClipboardManager)service.getSystemService(service.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("label", "A00僵尸粉-"+currentName.replaceAll("A00僵尸粉-",""));
                clipboard.setPrimaryClip(clip);
                nameInput.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                nameInput.performAction(AccessibilityNodeInfo.ACTION_PASTE);

            }
            AccessibilityHelper.performClick(AccessibilityHelper.findNodeInfosById(service.getRootInActiveWindow(),WXIDManage.getSaveNickNameButId(weixinversion)));
        }catch (Exception e){
            Log.e("修改昵称失败",e.getMessage());

        }
        isJSFans=false;
        AccessibilityHelper.performBack(service);



    }
    /**
     * uI更新
     */
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what){
                case CHECK:
                    tvCleanNumber.setText(cleanNumber+"/"+totalCleanNum);
                    msgText.setText("正在检测:"+currentName);
                    tvStatus.setTextColor(ContextCompat.getColor(service.getBaseContext(),R.color.gray));
                    tvStatus.setText(">>>");
                    break;
                case CHECK_END:
                        if(msg.arg1==1){
                            tvStatus.setTextColor(ContextCompat.getColor(service.getBaseContext(),R.color.green));
                            tvStatus.setText("OK");
                        }else {
                            tvStatus.setTextColor(ContextCompat.getColor(service.getBaseContext(),R.color.red));
                            tvStatus.setText("僵尸粉");
                            JSFirends.add(currentName);
                            adapter.notifyDataSetChanged();
                        }
                    break;
            }

        };
    };


    /**
     * 创建窗口
     */
    private void createWindow(){
        viewAdded=true;
        view = LayoutInflater.from(service).inflate(R.layout.clean_friends_window, null);
        view.findViewById(R.id.stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            onStopJob();
            }
        });
        time3=view.findViewById(R.id.time3);
        a1=view.findViewById(R.id.a1);
        tvStatus=view.findViewById(R.id.status);
        msgText=view.findViewById(R.id.msgText);
        animIcon=view.findViewById(R.id.animIcon);
        recyclerView=view.findViewById(R.id.listView);
        adapter=new XRecyclerViewAdapter(recyclerView,JSFirends,R.layout.clean_friends_item) {
            @Override
            protected void bindData(XViewHolder holder, Object o, int i) {
                holder.setText(R.id.nickName,o.toString());
            }
        };
        tvCleanNumber=view.findViewById(R.id.cleanNumber);
        tvCleanNumber.setText("0/"+totalCleanNum);
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(new DividerDecoration(Color.TRANSPARENT, XDensityUtils.dp2px(1)));
        recyclerView.setLayoutManager(new LinearLayoutManager(service.getBaseContext()));
        recyclerView.setAdapter(adapter);
        windowManager= (WindowManager) service.getSystemService(service.WINDOW_SERVICE);
        /*
         * LayoutParams.TYPE_SYSTEM_ERROR：保证该悬浮窗所有View的最上层
         * LayoutParams.FLAG_NOT_FOCUSABLE:该浮动窗不会获得焦点，但可以获得拖动
         * PixelFormat.TRANSPARENT：悬浮窗透明
         */
        layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,
        WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSPARENT);
        layoutParams.flags = layoutParams.flags | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
        layoutParams.flags = layoutParams.flags | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS; // 排版不受限制
        //悬浮窗开始在右下角显示
        layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        startWarp=view.findViewById(R.id.startWarp);
        mainWarp=view.findViewById(R.id.mainWarp);
        timepicker=view.findViewById(R.id.timepicker);
        windowManager.addView(view,layoutParams);
        new Timer(timepicker, new Timer.OnCountTimerListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
            @Override
            public void onFinish() {
                startWarp.setVisibility(View.GONE);
                mainWarp.setVisibility(View.VISIBLE);
                a1.startAnimation(createRotateAnimation(360,-360,5000));
                time3.setBase(SystemClock.elapsedRealtime());//计时器清零
                int hour = (int) ((SystemClock.elapsedRealtime() - time3.getBase()) / 1000 / 60);
                time3.setFormat("0"+String.valueOf(hour)+":%s");
                time3.start();

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        toContactPage();
                        selectContact();

                    }
                },200);


            }
        }).start();

    }

    /**
     * 创建旋转动画
     */
    private RotateAnimation createRotateAnimation(int fromDegress,int toDegrees,int duration) {
        RotateAnimation animation = new RotateAnimation(fromDegress, toDegrees, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        //动画执行时间
        animation.setDuration(duration);
        animation.setInterpolator(new LinearInterpolator());
        //动画重复次数-1表示不停重复
        animation.setRepeatCount(-1);
        return  animation;
    }



}
